/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.web.mail.controller;

import com.google.appengine.repackaged.org.apache.commons.httpclient.URI;
import com.google.appengine.repackaged.org.apache.commons.httpclient.URIException;

import com.sun.mail.pop3.POP3SSLStore;
import java.io.*;
import java.util.*;
import javax.activation.DataHandler;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.FlagTerm;

import queenb.net.entitybean.M575;
import queenb.web.controller.QueenbController;
import queenb.web.mail.inteface.M575Inf;
import queenb.web.mail.store.M575Store;
import queenb.web.util.ComboboxUtil;
import queenb.web.util.SessionProvider;
import queenb.web.util.Util;
import org.richfaces.model.UploadItem;
import org.richfaces.event.UploadEvent;
import queenb.net.entitybean.*;
import queenb.web.crm.controller.CustomerExpand;
import queenb.web.crm.controller.V030controller;
import queenb.web.crm.store.CustomerStore;
import queenb.web.store.M200Store;
import queenb.web.store.M650Store;
import queenb.web.store.Q100Store;
import queenb.web.util.*;

/**
 *
 * @author DUYNGUYEN
 */
public class MailSeverController extends QueenbController {

    private ComboboxUtil comboxUtil = new ComboboxUtil();
    private int fb050;
    private M575Inf m575Inf;
    private int pm575;
    private int ff150;
    private String mv576;
    private String mv577;
    private String mv578;
    private String mv579;
    private Date md580 = new Date();
    private int mn581;
    private int fh000;
    private int fh200;
    private int fq100;
    private String fm525 = "A";
    private String mv276 = "TO";
    private String mv277 = "M";
    private String hoten;
    private String title;
    private String html;
    private String text;
    private int renderMail = 0;
    private Date sendtime;
    private String reload;
    private static int intreload;
    private List<M575> listToFromMail;
    private List<M575> listToFromMailEx;
    private List<M575> listToFromMailSever;
    private String loginGmailYahoo;
    private String passwordGmailYahoo;
    private M575Store m575Store = new M575Store();
    private M650Store m650Store = new M650Store();
    private static Map<Integer, String> map = new HashMap<Integer, String>();
    private List<Map.Entry<Integer, String>> listSendMail;
    private List<ItemMail> listItemMail = new ArrayList<ItemMail>();
    private String fromMail;
    private String toMail;
    private String dateSend;
    private String titleMail;
    private String content;
    private List<ItemMail> listitem = new ArrayList<ItemMail>();
    private String colorchose = "";
    private String stylefrommail = "none";
    //send email 
    private static ArrayList<File> files = new ArrayList<File>();
    private String subjectMail;
    private String contentMail;
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final int SMTP_HOST_PORT = 465;
    private String SMTP_AUTH_USER = "";
    private String SMTP_AUTH_PWD = "";
    private String methodSend = "TO";
    private String listInfo = "";
    private String listInfoTo = "";
    private List<MailItem> listMail = new ArrayList<MailItem>();
    private String s = "";
    private Boolean chkMess = false;
    private Boolean chkMessS = false;
    private String filetemp;
    private String mailBox = "HỘP THƯ ĐẾN";
    // sendEmail for Email
    private int idcus;
    private String emailcus;
    private String typecus;
    private Boolean senper = false;
    private String pageRequest;
    private String check = "E";
    private int sttTitle = 2;
    private M200Store m200Store = new M200Store();
    private int pm200;
    private String listmail;
    private List<SelectItem> listcomboM200;
    private int typesearchKH;
    private String keysearchKH;
    private List<N100> listdifn100;
    private List<N100> listSelected = new ArrayList<N100>();
    
    private String mailrevice = "";
    private int mailreviceId;
    private String mailrevicepass = "";

    public MailSeverController() {

        getKapiMenu().setAdmin(false);

        Object objAction = getRequest().getParameter("action");
        System.out.println("------------action-----------" + objAction);

        Object objpage = getRequest().getParameter("page");
        Object sesspage = SessionProvider.getSessionMapValue("pageaction");
        if (sesspage != null && objpage == null) {
            objpage = sesspage;
            pageRequest = objpage.toString();
        } else if (objpage != null) {
            SessionProvider.setSessionMapValue("pageaction", objpage);
            pageRequest = objpage.toString();
        }





        getKapiMenu().setMainmenu1("m191"); // Hien thi Menu nao dc chon
        System.out.println("========================================listMail" + listInfo);
        if (objAction != null) {
            if (objAction.equals("come_person")) {
                Object objKey = getRequest().getParameter("key");
                map.remove(Integer.parseInt(objKey.toString()));
                listSendMail = new ArrayList(map.entrySet());
                if (listSendMail != null) {
                    stylefrommail = "block";
                } else {
                    stylefrommail = "none";
                }
                System.out.println("objkey-----------------" + objKey);
            }
//
            if (objAction.equals("inbox")) {

                Object objOutbox = getRequest().getParameter("mv276");
                mailBox = "HỘP THƯ ĐẾN";
                sttTitle = 2;
                if (objOutbox != null) {
                    System.out.println("Danh sach mail da nhan !");
                    this.mv276 = objOutbox.toString();
                  
                }
            }
            if (objAction.equals("delete")) {
                Object objOutbox = getRequest().getParameter("fm525");
                mailBox = "THƯ ĐÃ XÓA";
                sttTitle = 3;
                if (objOutbox != null) {
                    System.out.println("Danh sach mail da xoa !");
                    this.fm525 = objOutbox.toString();
                    System.out.println("D:- danh sach mail bị xoa ! getListM275(mv276, 0, fm525): " + mv276 + "," + 0 + " , " + fm525);
                    //listToFromMailEx = getListM275Ex(mv276, 0, fm525);
                }
            }
            if (objAction.equals("maildetail")) {
                Object pnFM575 = getRequest().getParameter("pm575");
                Object objMv276 = getRequest().getParameter("mv276");
                if (objMv276 != null) {
                    System.out.println("-----------------mv272----" + objMv276);
                    this.mv276 = objMv276.toString();
                    listToFromMail = getListM275(mv276, 0);
                }
                colorchose = "#4A5763";
                if (pnFM575 != null) {
                    this.pm575 = Integer.parseInt(pnFM575.toString());
                    List<M575> listDetail = getListM275(mv276, pm575);
                    renderMail = 1;
                    if (listDetail != null) {
                        Iterator iterator = listDetail.iterator();
                        while (iterator.hasNext()) {
                            M575 m575 = (M575) iterator.next();
                            this.pm575 = m575.getPm575();
                            System.out.println("-text--------------------->" + m575.getText());
                            this.mv578 = m575.getText();
                            this.hoten = m575.getHoten();
                            this.title = m575.getTitle();
                            this.sendtime = m575.getSendtime();
                            this.fq100 = m575.getFq100();
                        }
                    }
                }

            }
            if (objAction.equals("reply")) {
                Object objQ100 = getRequest().getParameter("fq100");
                this.fq100 = Integer.parseInt(objQ100.toString());

                Object objTitle = getRequest().getParameter("title");
                this.mv576 = objTitle.toString();
                System.out.println("----------mv576-------------" + mv576);
            } else if (objAction.equals("clear")) {
                listSelected.clear();
                SessionProvider.setSessionMapValue("listSelectedMail", null);
            }

            ////listToFromMail = getListM275(mv276, 0);


        }

        // getparamater for send mail 
//        this.senper=false;
        Q100Store storeQ100 = new Q100Store();
        Object objid = getRequest().getParameter("idx");
        Object objmail = getRequest().getParameter("mailx");
        Object objtype = getRequest().getParameter("typex");
        if (objid != null && objmail != null && objtype != null) {
            try {
                this.idcus = Integer.parseInt(objid.toString());
                this.emailcus = objmail.toString().trim();
                this.typecus = objtype.toString().trim();
                System.out.println("D:- sendmail nhan vien : id:= " + objid.toString() + ", email:= " + objmail.toString());
                if (idcus == -1) {
                    System.out.println("D:- Khong xac dinh duoc id :=" + idcus);
                    idcus = storeQ100.getIdByUserLogin(emailcus);
                    SessionProvider.setSessionMapValue("idcus", idcus);
                    SessionProvider.setSessionMapValue("inout", "I");
                    System.out.println("D:- set id:=" + idcus + " of email: " + emailcus);
                } else {
                    System.out.println("D:- Xac dinh duoc id : " + objid.toString());
                    SessionProvider.setSessionMapValue("idcus", objid);
                    SessionProvider.setSessionMapValue("inout", "E");
                }

                SessionProvider.setSessionMapValue("emailcus", objmail);
                SessionProvider.setSessionMapValue("typecus", objtype);
                this.senper = true;
            } catch (Exception e) {
                System.out.println("D:-- sendmail to person: " + e.getMessage());
                this.idcus = Integer.parseInt("0");
                this.emailcus = "";
                this.typecus = "";
                this.senper = false;
            }
        } else {
            try {
                this.idcus = Integer.parseInt(SessionProvider.getSessionMapValue("idcus").toString());
                this.emailcus = SessionProvider.getSessionMapValue("emailcus").toString();
                this.typecus = SessionProvider.getSessionMapValue("typecus").toString();
            } catch (Exception e) {
                System.out.println("D:-- sendmail to person: " + e.getMessage());
                this.idcus = Integer.parseInt("0");
                this.emailcus = "";
                this.typecus = "";
                this.senper = false;
            }
        }

        Object objide = getRequest().getParameter("ide");
        Object objidq = getRequest().getParameter("idq");
        Object objstatus = getRequest().getParameter("status");
        if (objide != null && objstatus != null) {
            try {
                System.out.println("D:- chuyen trang thai email: id:= " + objide + "Status:= " + objstatus.toString() + " objidq : " + objidq);
                int ide = Integer.parseInt(objide.toString());
                int idq = 0;
                if (objidq != null) {
                    idq = Integer.parseInt(objidq.toString());
                }
                String status = objstatus.toString();
                m575Store.updateM275OneColumn(null, "M275", "FM525", status, "PM275", ide, getLogin().getUserName());
                if (status.equals("D")) {
                    if (objidq != null) {
                        System.out.println("D:- Delete mail !");
                        m575Store.deleteM275(ide, idq, getLogin().getUserName());
                    }

                } else if (status.equals("R")) {
                    if (objidq != null) {
                        System.out.println("D:- restore mail !");
                        m575Store.restoreM275(ide, idq, getLogin().getUserName());
                    }

                }
            } catch (Exception e) {
                System.out.println("D:- Error from chuyen trang thai Email: " + e.getMessage());
            }
        }


    }

    public void listener(UploadEvent event) throws Exception {

        UploadItem item = event.getUploadItem();

        String path = item.getFile().getPath();

        int myIndex = 0;
        int l = path.length();
        for (int i = path.length() - 1; i > 0; i--) {
            if (path.charAt(i) == '\\') {
                myIndex = i;
                break;
            }
        }

        String temp = path.substring(myIndex + 1, l);
        String path2 = path.replaceAll(temp, item.getFileName());

        if ((new File(path2)).exists()) {
            (new File(path2)).delete();
        }

        File file = new File(path);
        file.renameTo(new File(path2));
        File file2 = new File(path2);
        files.add(file2);
        System.out.println(" DANH SACH TAP TIN DINH KEM!");
        for (File filetemp : files) {
            System.out.println("-- " + filetemp.getName() + "--- " + filetemp.getPath());
        }
    }

    // Search nhân viên trong form công ty TÙNG
    public void reloadform(ActionEvent event) {
        System.out.println("---------------------AADD-------" + keysearchKH + getTypesearchKH());
        SessionProvider.setSessionMapValue("KEYKH", keysearchKH);// tim kiếm lahcsh hang cho cong ty
    }

    public void actionListenner() {

        System.out.println("D:-- filetemp : " + getFiletemp());
        int a = Integer.parseInt(getFiletemp());
        if (a == 1) {
            contentMail = "----------------tempalte 1 -------------";
        } else if (a == 2) {
            contentMail = "----------------tempalte 2 -------------";
        } else if (a == 3) {
            contentMail = "----------------tempalte 2 -------------";
        }
    }

    public List<SelectItem> getSelectItemB050() {
        return comboxUtil.getListCombB050();
    }

    public List<SelectItem> getSelectItemQ100() {
        try {
            return comboxUtil.getListCombQ100();
        } catch (Exception ex) {
            return null;
        }
    }

    public List<M575> getListM275(String mv276, int pnFM575) {

        if (getLogin() != null) {
            int idx = getLogin().getId();
            System.out.println("list--->" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "I" + "," + getLogin().getUserName());
            try {
                List<M575> listM275 = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, "A", mv276, "I",mailrevice,0,10000,0,0, getLogin().getUserName());
                return listM275;
            } catch (Exception ex) {
                System.out.println("D: -- Error from getListM275: " + ex.getMessage());
                return new ArrayList<M575>();
            }
        } else {
            System.out.println("D: -- Error from getListM275: ");
            sendRedirect("login.jsp");
            return new ArrayList<M575>();
        }

    }

//    public List<M575> getListM275(String mv276, int pnFM575, String fm525) {
//
//        if (getLogin() != null) {
//            int idx = getLogin().getId();
//            System.out.println("list--->" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "I" + "," + getLogin().getUserName());
//            try {
//                List<M575> listM275TO = new ArrayList<M575>();
//                listM275TO = m575Store.getListTabM275D(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), "TO", "I", getLogin().getUserName());
//                if (listM275TO != null) {
//                    List<M575> listM275FROM = new ArrayList<M575>();
//                    listM275FROM = m575Store.getListTabM275D(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), "FROM", "I", getLogin().getUserName());
//                    for (M575 m575 : listM275FROM) {
//                        listM275TO.add(m575);
//                    }
//                }
//                return listM275TO;
//            } catch (Exception ex) {
//                System.out.println("D: -- Error from getListM275: " + ex.getMessage());
//                return new ArrayList<M575>();
//            }
//        } else {
//            System.out.println("D: -- Error from getListM275: ");
//            sendRedirect("login.jsp");
//            return new ArrayList<M575>();
//        }
//
//    }

    public List<M575> getListM275Ex(String mv276, int pnFM575) {

        if (getLogin() != null) {
            int idx = getLogin().getId();
            System.out.println("listabc--->" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "D" + "," + getLogin().getUserName());
            try {
                List<M575> listM275 = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), mv276, "D",mailrevice,0,10000,0,0, getLogin().getUserName());
                return listM275;
            } catch (Exception ex) {
                System.out.println("D: -- Error from getListM275: " + ex.getMessage());
                return new ArrayList<M575>();
            }
        } else {
            System.out.println("D: -- Error from getListM275: ");
            sendRedirect("login.jsp");
            return new ArrayList<M575>();
        }

    }

//    public List<M575> getListM275Ex(String mv276, int pnFM575, String fm525) {
//        if (getLogin() != null) {
//            int idx = getLogin().getId();
//            System.out.println("list--->" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "D" + "," + getLogin().getUserName());
//            try {
//                List<M575> listM275TO = new ArrayList<M575>();
//                listM275TO = m575Store.getListTabM275D(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), "TO", "D", getLogin().getUserName());
//                return listM275TO;
//            } catch (Exception ex) {
//                System.out.println("D: -- Error from getListM275: " + ex.getMessage());
//                return new ArrayList<M575>();
//            }
//        } else {
//            System.out.println("D: -- Error from getListM275: ");
//            sendRedirect("login.jsp");
//            return new ArrayList<M575>();
//        }
//
//    }

//    public void saveM575() {
//        int roweffect = 0;
//        try {
//            System.out.println("update--" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + this.getPm575() + "," + 1 + "," + this.getMv576() + "," + this.getMv577() + "," + this.getMv578() + "," + this.getMv579() + "," + Util.toSQLDate(new Date()) + "," + 0 + "," + getLogin().getUserName());
//            roweffect = m575Inf.updateM575By(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), this.getPm575(), 1, this.getMv576(), this.getMv577(), this.getMv578(), this.getMv579(), Util.toSQLDate(new Date()), 0, "I",mailrevice, getLogin().getUserName());
//            System.out.println("---------row----------" + roweffect);
//            if (roweffect > 0) {
//                Iterator icMap = map.entrySet().iterator();
//                while (icMap.hasNext()) {
//                    Map.Entry mapEntry = (Map.Entry) icMap.next();
//                    m575Inf.updateM275(roweffect, roweffect, Integer.parseInt(mapEntry.getKey().toString()), "A", "TO", "I", "S", null, getLogin().getUserName());
//                }
//            }
//
//            reload = "<script type='text/javascript'>self.parent.tb_remove()</script>";
//            listToFromMail = getListM275("TO", 0);
//            map.clear();
//
//
//
//        } catch (Exception ex) {
//            showGlobalReport(true, getResourceString("datasuccessfail"));
//            sendRedirect("mail.jsp");
//        }
//
//
//    }

    public List<M575> getListToFromMail() {
        if (listToFromMail == null) {
            System.out.println("D:- call list !");
            listToFromMail = getListM275(mv276, 0);
            mailBox = "Hộp THƯ ĐẾN";
        }


        return listToFromMail;
    }

    public void actionListenner(ActionEvent evt) {
        String come_person = "";
        Iterator ic = comboxUtil.getListCombQ100().iterator();
        while (ic.hasNext()) {
            SelectItem item = (SelectItem) ic.next();

            if (this.getFq100() == Integer.parseInt(item.getValue().toString())) {
                System.out.println("---------m851----------" + item.getValue() + "----------" + item.getLabel());
                getMap().put(this.getFq100(), item.getLabel());
            }
        }
        listSendMail = new ArrayList(map.entrySet());
        if (listSendMail != null) {
            stylefrommail = "block";
        } else {
            stylefrommail = "none";
        }
        Iterator icMap = map.entrySet().iterator();
        while (icMap.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) icMap.next();
            come_person += mapEntry.getValue();
            come_person += ",";
            System.out.println("--vvvvvvvvvvvvvvvvvvv--" + come_person + "-----------vkey--" + mapEntry.getKey());

        }
        //setMv576(come_person);


    }

    //cau hinh mail gmail - yahoo
//    public Store storeGmailYahoo(String userMailYahoo, String passwordMailYahoo) {
//        Session session = null;
//        Store store = null;
//        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//        Properties pop3Props = new Properties();
//        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
//        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
//        pop3Props.setProperty("mail.pop3.port", "995");
//        pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
//        URLName url = new URLName("pop3", "pop.gmail.com", 995, "",
//                userMailYahoo, passwordMailYahoo);
//
//        session = Session.getInstance(pop3Props, null);
//        store = new POP3SSLStore(session, url);
//        try {
//            return store;
//        } catch (Exception ex) {
//            System.out.println("-------" + ex.getMessage());
//            return null;
//        }
//    }
//
//    public void check() {
//
//        try {
//
//            GmailUtilities gmail = new GmailUtilities();
//            gmail.setUserPass(" ", "");
//            gmail.connect();
//            gmail.openFolder("INBOX");
//
//            int totalMessages = gmail.getMessageCount();
//            int newMessages = gmail.getNewMessageCount();
//
//            System.out.println("Total messages = " + totalMessages);
//            System.out.println("New messages = " + newMessages);
//            System.out.println("-------------------------------");
//
//            //gmail.printAllMessageEnvelopes();
//            gmail.printAllMessages();
//
//        } catch (Exception e) {
//            System.out.println("D:--Eror from getMail from Gmail: " + e.getMessage());
//            e.printStackTrace();
//            System.exit(-1);
//        }
//    }
//    public List<M575> getListToFromMailSever() throws IOException, MessagingException {
//        Properties props = new Properties();
//        
//        props.put("mail.transport.protocol", "smtps");
//        props.put("mail.smtp.host", SMTP_HOST_NAME);
//        props.put("mail.smtps.auth", "true");
//        props.put("mail.smtp.starttls.enable", "true");
//        props.put("mail.smtps.from", "kakaka@machine");
//        props.setProperty("mail.store.protocol", "imaps");
//        props.setProperty("mail.imap.host", "imap.gmail.com");
//        props.setProperty("mail.imap.port", "993");
//        props.setProperty("mail.imap.connectiontimeout", "5000");
//        props.setProperty("mail.imap.timeout", "5000");
//        try {
//            Session session = Session.getDefaultInstance(props, null);
//            Store store = session.getStore("imaps");
//            store.connect("imap.gmail.com", "saotitan.sao@gmail.com", "saotitan2011");
//            System.out.println(store);
//            
//            Folder inbox = store.getFolder("Inbox");
//            inbox.open(Folder.READ_ONLY);
//            Message messages[] = inbox.getMessages();
//            System.out.println("D:--------------------------inbox------------------------");
//            for (Message message : messages) {
////
//                System.out.println("SentDate : " + message.getSentDate());
//                String from = message.getFrom()[0].toString();
//                System.out.println("From : " + from);
//                System.out.println("Subject : " + message.getSubject());
//                System.out.println("D:--" + message);
//            }
//        } catch (NoSuchProviderException e) {
//            e.printStackTrace();
//            System.exit(1);
//        } catch (MessagingException e) {
//            e.printStackTrace();
//            System.exit(2);
//        }
//        return listToFromMailSever;
//    }
//    public List<ItemMail> getListItemMailCcheck() throws IOException, MessagingException {
//        System.out.println("-----------re mail -------------------");
//
//        if (listitem != null && listitem.size() > 0) {
//            Session session = null;
//            Store store = null;
//            String username, password;
//
//            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//
//            Properties pop3Props = new Properties();
//
//            pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
//            pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
//            pop3Props.setProperty("mail.pop3.port", "995");
//            pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
//
//            URLName url = new URLName("pop3", "pop.gmail.com", 995, "",
//                    "saotitan.sao@gmail.com", "saotitan2011");
//
//            session = Session.getInstance(pop3Props, null);
//            store = new POP3SSLStore(session, url);
//            try {
//                store.connect();
//
//            } catch (Exception ex) {
//                System.out.println("-------" + ex.getMessage());
//            }
//
//
//
//            Folder folder = store.getFolder("inbox");
//
//            // Open the Folder.
//            folder.open(Folder.READ_ONLY);
//
//            Message[] message = folder.getMessages();
//
//            // Display message.
//            for (int i = 0; i < message.length; i++) {
//
//                System.out.println("------------ Message " + (i + 1) + " ------------");
//
//                System.out.println("SentDate : " + message[i].getSentDate());
//                String from = message[i].getFrom()[0].toString();
//                ItemMail item = new ItemMail();
//                item.setFromMail(from);
//                listitem.add(item);
//                SessionProvider.setSessionMapValue("listitem", listitem);
//                System.out.println("From : " + from);
//                System.out.println("Subject : " + message[i].getSubject());
//                System.out.print("Message : ");
//
////  InputStream stream = message[i].getInputStream();
////  while (stream.available() != 0) {
////  System.out.print((char) stream.read());
////  }
////  System.out.println();
//            }
//
//            folder.close(true);
//            store.close();
//        }
//        return listitem;
//    }
    /**
     * @return the fb050
     */
    public int getFb050() {
        return fb050;
    }

    /**
     * @param fb050 the fb050 to set
     */
    public void setFb050(int fb050) {
        this.fb050 = fb050;
    }

    /**
     * @return the m575Inf
     */
    public M575Inf getM575Inf() {
        return m575Inf;
    }

    /**
     * @param m575Inf the m575Inf to set
     */
    public void setM575Inf(M575Inf m575Inf) {
        this.m575Inf = m575Inf;
    }

    /**
     * @return the pm575
     */
    public int getPm575() {
        return pm575;
    }

    /**
     * @param pm575 the pm575 to set
     */
    public void setPm575(int pm575) {
        this.pm575 = pm575;
    }

    /**
     * @return the ff150
     */
    public int getFf150() {
        return ff150;
    }

    /**
     * @param ff150 the ff150 to set
     */
    public void setFf150(int ff150) {
        this.ff150 = ff150;
    }

    /**
     * @return the mv576
     */
    public String getMv576() {
        return mv576;
    }

    /**
     * @param mv576 the mv576 to set
     */
    public void setMv576(String mv576) {
        this.mv576 = mv576;
    }

    /**
     * @return the mv577
     */
    public String getMv577() {
        return mv577;
    }

    /**
     * @param mv577 the mv577 to set
     */
    public void setMv577(String mv577) {
        this.mv577 = mv577;
    }

    /**
     * @return the mv578
     */
    public String getMv578() {
        return mv578;
    }

    /**
     * @param mv578 the mv578 to set
     */
    public void setMv578(String mv578) {
        this.mv578 = mv578;
    }

    /**
     * @return the mv579
     */
    public String getMv579() {
        return mv579;
    }

    /**
     * @param mv579 the mv579 to set
     */
    public void setMv579(String mv579) {
        this.mv579 = mv579;
    }

    /**
     * @return the md580
     */
    public Date getMd580() {
        return md580;
    }

    /**
     * @param md580 the md580 to set
     */
    public void setMd580(Date md580) {
        this.md580 = md580;
    }

    /**
     * @return the mn581
     */
    public int getMn581() {
        return mn581;
    }

    /**
     * @param mn581 the mn581 to set
     */
    public void setMn581(int mn581) {
        this.mn581 = mn581;
    }

    /**
     * @return the fh000
     */
    public int getFh000() {
        return fh000;
    }

    /**
     * @param fh000 the fh000 to set
     */
    public void setFh000(int fh000) {
        this.fh000 = fh000;
    }

    /**
     * @return the fh200
     */
    public int getFh200() {
        return fh200;
    }

    /**
     * @param fh200 the fh200 to set
     */
    public void setFh200(int fh200) {
        this.fh200 = fh200;
    }

    /**
     * @return the reload
     */
    public String getReload() {
        return reload;
    }

    /**
     * @param reload the reload to set
     */
    public void setReload(String reload) {
        this.reload = reload;
    }

    /**
     * @return the intreload
     */
    public int getIntreload() {
        return intreload;
    }

    /**
     * @param intreload the intreload to set
     */
    public void setIntreload(int intreload) {
        this.intreload = intreload;
    }

    /**
     * @return the map
     */
    public Map<Integer, String> getMap() {
        return map;
    }

    /**
     * @param map the map to set
     */
    public void setMap(Map<Integer, String> map) {
        this.map = map;
    }

    /**
     * @return the listSendMail
     */
    public List<Map.Entry<Integer, String>> getListSendMail() {
        return listSendMail;
    }

    /**
     * @param listSendMail the listSendMail to set
     */
    public void setListSendMail(List<Map.Entry<Integer, String>> listSendMail) {
        this.listSendMail = listSendMail;
    }

    /**
     * @return the fq100
     */
    public int getFq100() {
        return fq100;
    }

    /**
     * @param fq100 the fq100 to set
     */
    public void setFq100(int fq100) {
        this.fq100 = fq100;
    }

    /**
     * @return the fm525
     */
    public String getFm525() {
        return fm525;
    }

    /**
     * @param fm525 the fm525 to set
     */
    public void setFm525(String fm525) {
        this.fm525 = fm525;
    }

    /**
     * @return the mv276
     */
    public String getMv276() {
        return mv276;
    }

    /**
     * @param mv276 the mv276 to set
     */
    public void setMv276(String mv276) {
        this.mv276 = mv276;
    }

    /**
     * @return the mv277
     */
    public String getMv277() {
        return mv277;
    }

    /**
     * @param mv277 the mv277 to set
     */
    public void setMv277(String mv277) {
        this.mv277 = mv277;
    }

    /**
     * @return the listToFromMail
     */
    /**
     * @param listToFromMail the listToFromMail to set
     */
    public void setListToFromMail(List<M575> listToFromMail) {
        this.listToFromMail = listToFromMail;
    }

    /**
     * @return the hoten
     */
    public String getHoten() {
        return hoten;
    }

    /**
     * @param hoten the hoten to set
     */
    public void setHoten(String hoten) {
        this.hoten = hoten;
    }

    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @return the html
     */
    public String getHtml() {
        return html;
    }

    /**
     * @param html the html to set
     */
    public void setHtml(String html) {
        this.html = html;
    }

    /**
     * @return the text
     */
    public String getText() {
        return text;
    }

    /**
     * @param text the text to set
     */
    public void setText(String text) {
        this.text = text;
    }

    /**
     * @return the sendtime
     */
    public Date getSendtime() {
        return sendtime;
    }

    /**
     * @param sendtime the sendtime to set
     */
    public void setSendtime(Date sendtime) {
        this.sendtime = sendtime;
    }

    /**
     * @return the renderMail
     */
    public int getRenderMail() {
        return renderMail;
    }

    /**
     * @param renderMail the renderMail to set
     */
    public void setRenderMail(int renderMail) {
        this.renderMail = renderMail;
    }

    /**
     * @return the loginGmailYahoo
     */
    public String getLoginGmailYahoo() {
        return loginGmailYahoo;
    }

    /**
     * @param loginGmailYahoo the loginGmailYahoo to set
     */
    public void setLoginGmailYahoo(String loginGmailYahoo) {
        this.loginGmailYahoo = loginGmailYahoo;
    }

    /**
     * @return the passwordGmailYahoo
     */
    public String getPasswordGmailYahoo() {
        return passwordGmailYahoo;
    }

    /**
     * @param passwordGmailYahoo the passwordGmailYahoo to set
     */
    public void setPasswordGmailYahoo(String passwordGmailYahoo) {
        this.passwordGmailYahoo = passwordGmailYahoo;
    }

    /**
     * @return the listItemMail
     */
    public List<ItemMail> getListItemMail() {

        return listItemMail;
    }

    /**
     * @param listItemMail the listItemMail to set
     */
    public void setListItemMail(List<ItemMail> listItemMail) {
        this.listItemMail = listItemMail;
    }

    /**
     * @return the fromMail
     */
    public String getFromMail() {
        return fromMail;
    }

    /**
     * @param fromMail the fromMail to set
     */
    public void setFromMail(String fromMail) {
        this.fromMail = fromMail;
    }

    /**
     * @return the toMail
     */
    public String getToMail() {
        return toMail;
    }

    /**
     * @param toMail the toMail to set
     */
    public void setToMail(String toMail) {
        this.toMail = toMail;
    }

    /**
     * @return the dateSend
     */
    public String getDateSend() {
        return dateSend;
    }

    /**
     * @param dateSend the dateSend to set
     */
    public void setDateSend(String dateSend) {
        this.dateSend = dateSend;
    }

    /**
     * @return the titleMail
     */
    public String getTitleMail() {
        return titleMail;
    }

    /**
     * @param titleMail the titleMail to set
     */
    public void setTitleMail(String titleMail) {
        this.titleMail = titleMail;
    }

    /**
     * @return the content
     */
    public String getContent() {
        return content;
    }

    /**
     * @param content the content to set
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @return the listitem
     */
    public List<ItemMail> getListitem() {
        listitem = (List<ItemMail>) SessionProvider.getSessionMapValue("listitem");
        return listitem;
    }

    /**
     * @param listitem the listitem to set
     */
    public void setListitem(List<ItemMail> listitem) {
        this.listitem = listitem;
    }

    /**
     * @return the colorchose
     */
    public String getColorchose() {
        return colorchose;
    }

    /**
     * @param colorchose the colorchose to set
     */
    public void setColorchose(String colorchose) {
        this.colorchose = colorchose;
    }

    /**
     * @return the stylefrommail
     */
    public String getStylefrommail() {
        return stylefrommail;
    }

    /**
     * @param stylefrommail the stylefrommail to set
     */
    public void setStylefrommail(String stylefrommail) {
        this.stylefrommail = stylefrommail;
    }

    /**
     * @return the subjectMail
     */
    public String getSubjectMail() {
        return subjectMail;
    }

    /**
     * @param subjectMail the subjectMail to set
     */
    public void setSubjectMail(String subjectMail) {
        this.subjectMail = subjectMail;
    }

    /**
     * @return the contentMail
     */
    public String getContentMail() {
        return contentMail;
    }

    /**
     * @param contentMail the contentMail to set
     */
    public void setContentMail(String contentMail) {
        this.contentMail = contentMail;
    }

    /**
     * @return the methodSend
     */
    public String getMethodSend() {
        return methodSend;
    }

    /**
     * @param methodSend the methodSend to set
     */
    public void setMethodSend(String methodSend) {
        this.methodSend = methodSend;
    }

    /**
     * @return the listInfo
     */
    public String getListInfo() {
        return listInfo;
    }

    /**
     * @param listInfo the listInfo to set
     */
    public void setListInfo(String listInfo) {
        this.listInfo = listInfo;
    }

    /**
     * @return the listMail
     */
    public List<MailItem> getListMail() {
        List<N100> listKH = new ArrayList<N100>();
        Object listselected = SessionProvider.getSessionMapValue("listSelectedMail");
        if (listselected != null) {
            try {
                listKH = (List<N100>) listselected;
            } catch (Exception e) {
                listKH = new ArrayList<N100>();
            }
        } else {
            listKH = new ArrayList<N100>();
        }

        for (int i = 0; i < listKH.size(); i++) {
            N100 cus = listKH.get(i);
            if (cus.getNv120() != null && cus.getNv120() != "" && cus.getNv120().contains("@")) {
                MailItem mail = new MailItem(cus.pn100, cus.getHoten(), cus.getNv120(), "", cus.getPronouns(), "");
                listMail.add(mail);
//                    listInfo += listKH.get(i).getNv105() + ";  ";
            }

        }
        return listMail;
    }

    /**
     * @param listMail the listMail to set
     */
    public void setListMail(List<MailItem> listMail) {
        this.listMail = listMail;
    }

    /**
     * @return the listInfoTo
     */
    public String getListInfoTo() {
        List<N100> listKH = new ArrayList<N100>();
        Object listselected = SessionProvider.getSessionMapValue("listSelectedMail");
        if (listselected != null) {
            try {
                listKH = (List<N100>) listselected;
            } catch (Exception e) {
                listKH = new ArrayList<N100>();
            }
        } else {
            listKH = new ArrayList<N100>();
        }

        for (int i = 0; i < listKH.size(); i++) {
            N100 cus = listKH.get(i);
            if (cus.getNv105() != null && cus.getNv105() != "" && cus.getNv105().contains("@")) {
                MailItem mail = new MailItem(cus.pn100, cus.getHoten(), cus.getNv105(), "", cus.getPronouns(), "");
//                    listMail.add(mail);
                listInfo += listKH.get(i).getNv105() + ";  ";
            }

        }
        return listInfoTo;
    }

    /**
     * @param listInfoTo the listInfoTo to set
     */
    public void setListInfoTo(String listInfoTo) {
        this.listInfoTo = listInfoTo;
    }

    /**
     * @return the s
     */
    public String getS() {
        return s;
    }

    /**
     * @param s the s to set
     */
    public void setS(String s) {
        this.s = s;
    }

    /**
     * @return the chkMess
     */
    public Boolean getChkMess() {
        return chkMess;
    }

    /**
     * @param chkMess the chkMess to set
     */
    public void setChkMess(Boolean chkMess) {
        this.chkMess = chkMess;
    }

    /**
     * @return the chkMessS
     */
    public Boolean getChkMessS() {
        return chkMessS;
    }

    /**
     * @param chkMessS the chkMessS to set
     */
    public void setChkMessS(Boolean chkMessS) {
        this.chkMessS = chkMessS;
    }

    /**
     * @return the filetemp
     */
    public String getFiletemp() {
        return filetemp;
    }

    /**
     * @param filetemp the filetemp to set
     */
    public void setFiletemp(String filetemp) {
        this.filetemp = filetemp;
    }

    /**
     * @return the idcus
     */
    public int getIdcus() {
        return idcus;
    }

    /**
     * @param idcus the idcus to set
     */
    public void setIdcus(int idcus) {
        this.idcus = idcus;
    }

    /**
     * @return the emailcus
     */
    public String getEmailcus() {
        return emailcus;
    }

    /**
     * @param emailcus the emailcus to set
     */
    public void setEmailcus(String emailcus) {
        this.emailcus = emailcus;
    }

    /**
     * @return the typecus
     */
    public String getTypecus() {
        return typecus;
    }

    /**
     * @param typecus the typecus to set
     */
    public void setTypecus(String typecus) {
        this.typecus = typecus;
    }

    /**
     * @return the senper
     */
    public Boolean getSenper() {
        return senper;
    }

    /**
     * @param senper the senper to set
     */
    public void setSenper(Boolean senper) {
        this.senper = senper;
    }

    /**
     * @return the pageRequest
     */
    public String getPageRequest() {
        return pageRequest;
    }

    /**
     * @param pageRequest the pageRequest to set
     */
    public void setPageRequest(String pageRequest) {
        this.pageRequest = pageRequest;
    }

    /**
     * @return the mailBox
     */
    public String getMailBox() {
//        if (mv276.equals("TO")) {
//            mailBox = "Hộp thư đến";
//        } else if (mv276.equals("FROM")) {
//            mailBox = "Thư đã gửi";
//        }
        return mailBox;
    }

    /**
     * @param mailBox the mailBox to set
     */
    public void setMailBox(String mailBox) {
        this.mailBox = mailBox;
    }

    /**
     * @return the listToFromMailEx
     */
    public List<M575> getListToFromMailEx() {
        System.out.println("D:- Danh sach mail gui ra ngoai !");
        if (listToFromMailEx == null) {
            mailBox = "HỘP THƯ ĐẾN";
            
        }

        return listToFromMailEx;
    }

    /**
     * @param listToFromMailEx the listToFromMailEx to set
     */
    public void setListToFromMailEx(List<M575> listToFromMailEx) {
        this.listToFromMailEx = listToFromMailEx;
    }

    /**
     * @return the check
     */
    public String getCheck() {
        return check;
    }

    /**
     * @param check the check to set
     */
    public void setCheck(String check) {
        this.check = check;
    }

    /**
     * @return the sttTitle
     */
    public int getSttTitle() {
        return sttTitle;
    }

    /**
     * @param sttTitle the sttTitle to set
     */
    public void setSttTitle(int sttTitle) {
        this.sttTitle = sttTitle;
    }

    public void changeAll(ActionEvent ac) {
        System.out.println("D:------------------------------------------------------abc");
    }

    public void change4ldv(ActionEvent ac) {
        List<M200> list = m200Store.getListM200All(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getId(), getLogin().getUserName());
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getPm200() == getPm200()) {
                    this.contentMail = (list.get(i).getMv202());
                    break;
                }
            }
        }

    }

    /**
     * @return the pm200
     */
    public int getPm200() {
        return pm200;
    }

    /**
     * @param pm200 the pm200 to set
     */
    public void setPm200(int pm200) {
        this.pm200 = pm200;
    }

    /**
     * @return the listmail
     */
    public String getListmail() {
        Object obj = SessionProvider.getSessionMapValue("listSelectedMail");
        if (obj != null) {
            listmail = "";
            try {
                List<N100> list = (List<N100>) obj;
                if (list != null && list.size() > 0) {
                    for (N100 n100 : list) {
                        listmail += n100.getHoten() + "; ";

                    }
                }
            } catch (Exception e) {
                listmail = "";
            }
        }
        System.out.println("D:- Danh sach: " + listmail);
        return listmail;
    }

    /**
     * @param listmail the listmail to set
     */
    public void setListmail(String listmail) {
        this.listmail = listmail;
    }

    /**
     * @return the listcomboM200
     */
    public List<SelectItem> getListcomboM200() {
        listcomboM200 = comboxUtil.getlistCombM200();
        return listcomboM200;
    }

    /**
     * @param listcomboM200 the listcomboM200 to set
     */
    public void setListcomboM200(List<SelectItem> listcomboM200) {
        this.listcomboM200 = listcomboM200;
    }

    /**
     * @return the listToFromMailSever
     */
//    public List<M575> getListToFromMailSever() {
//        Properties props = System.getProperties();
//        props.setProperty("mail.store.protocol", "imaps");
//        try {
//            Session session = Session.getDefaultInstance(props, null);
//            Store store = session.getStore("imaps");
//            store.connect("imap.gmail.com", "saotitan.sao@gmail.com", "saotitan2011");
//            System.out.println(store);
//
//            Folder inbox = store.getFolder("Inbox");
//            inbox.open(Folder.READ_ONLY);
//            //Message messages[] = inbox.getMessages();
//            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
//            Message messages[] = inbox.search(ft);
//
//            int i = 0;
//            for (Message message : messages) {
//
//                Multipart mp = (Multipart) messages[i].getContent();
//                Object p = mp.getBodyPart(i).getContent();
//                String q = p.toString();//object has the body content  
//                System.out.println(q);//prints the body  
//                System.out.println(messages[i].getSubject() + " \n" + i);
//                i++;
//            }
//
//
//        } catch (NoSuchProviderException e) {
//            e.printStackTrace();
//            System.exit(1);
//        } catch (MessagingException e) {
//            e.printStackTrace();
//            System.exit(2);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        return listToFromMailSever;
//    }
//    public List<M575> getListToFromMailSever() throws NoSuchProviderException, MessagingException, IOException {
//        String host = "pop.gmail.com";
//        String user = (getLogin() != null)? getLogin().getQv117():"";
//        String password = (getLogin() != null)? getLogin().getQv118():"";
//        System.out.println("D:- UP: "+ user +" - "+ password);
//
//        // Get system properties
//        Properties properties = System.getProperties();
//
//        // Get the default Session object.
//        Session session = Session.getDefaultInstance(properties);
//
//        // Get a Store object that implements the specified protocol.
//        Store store = session.getStore("pop3");
//
//        //Connect to the current host using the specified username and password.
//        store.connect(host, user, password);
//
//        //Create a Folder object corresponding to the given name.
//        Folder folder = store.getFolder("inbox");
//
//        // Open the Folder.
//        folder.open(Folder.READ_ONLY);
//
//        Message[] message = folder.getMessages();
//
//        // Display message.
//        for (int i = 0; i < message.length; i++) {
//
//            System.out.println("------------ Message " + (i + 1) + " ------------");
//
//            System.out.println("SentDate : " + message[i].getSentDate());
//            System.out.println("From : " + message[i].getFrom()[0]);
//            System.out.println("Subject : " + message[i].getSubject());
//            System.out.print("Message : ");
//
////            InputStream stream = message[i].getInputStream();
////            while (stream.available() != 0) {
////                System.out.print((char) stream.read());
////            }
////            System.out.println();
//        }
//
//        folder.close(true);
//        store.close();
//        
//        return listToFromMailSever;
//    }
//    public List<M575> getListToFromMailSever() {
//        List<File> attachments = new ArrayList<File>();
//        Properties props = System.getProperties();
//
//        String host = "pop.gmail.com";
//
//        final String username = (getLogin() != null) ? getLogin().getQv119() : "";
//
//        final String password = (getLogin() != null) ? getLogin().getQv120() : "";
//
//        String provider = "pop3s";
//        try {
//            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//            props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
//            props.setProperty("mail.pop3.socketFactory.fallback", "false");
//            props.setProperty("mail.pop3.port", "995");
//            props.setProperty("mail.pop3.socketFactory.port", "995");
//            props.put("mail.pop3.host", "pop.gmail.com");
//            props.put("mail.smtp.host", "pop.gmail.com");
//            props.put("mail.smtp.port", "587");
//            props.put("mail.smtp.starttls.enable", "true");
//
//            javax.mail.Authenticator pa = null; //default: no authentication
//
//            if (username != null && password != null) {
//
//                props.put("mail.smtp.auth", "true");
//
//                pa = new javax.mail.Authenticator() {
//
//                    public PasswordAuthentication getPasswordAuthentication() {
//
//                        return new PasswordAuthentication(username, password);
//
//                    }
//                };
//
//            }//else: no authentication
//
//            // Kết nối đến POP3 server
//
//            Session session = Session.getDefaultInstance(props, pa);
//
//            Store store = session.getStore(provider);
//
//            store.connect(host, username, password);
//
//            // Mở thư mục INBOX
//
//            Folder inbox = store.getFolder("inbox");
//
//            if (inbox == null) {
//
//                System.out.println("No INBOX");
//
//                System.exit(1);
//
//            }
//            inbox.open(Folder.READ_ONLY);
//
//
//            // Lấy messages từ server
////            Message messages[] = inbox.getMessages();
//
//            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
//
//            Message messages[] = inbox.search(ft);
//            FetchProfile fp = new FetchProfile();
//            fp.add(FetchProfile.Item.ENVELOPE);
//            fp.add(FetchProfile.Item.CONTENT_INFO);
//            inbox.fetch(messages, fp);
//
//            if (messages.length < 1 || messages == null) {
//                System.out.println("Không có mail mới nào cả!");
//            } else {
////                System.out.println("Số lương Mail: " + messages.length);
//
//                for (int messageCount = 0; messageCount < messages.length; messageCount++) {
//                    messages[messageCount].setFlag(Flags.Flag.SEEN, true);
//                    String from = messages[messageCount].getFrom()[0].toString().trim();
//                    String fromcv = Util.removeQuotes(from).trim();
////                    System.out.println("From: -"+from+"-");
////                    System.out.println("Fromcv: -"+fromcv+"-");
////                    System.out.println("username: -"+username+"-");
////                    System.out.println("from.equals(username) : "+ from.equals(username));
////                    System.out.println("fromcv.equals(username) : "+ fromcv.equals(username));
////                    System.out.println("username.equals(fromcv) : "+ username.equals(fromcv));
//                    if (username.equals(fromcv)) {
//                        continue;
//                    }
//                    List<AttachItem> listAttach = new ArrayList<AttachItem>();
//                    System.out.println("Mail number : " + messages[messageCount].getMessageNumber());
//                    try {
//                        Message aMessage = messages[messageCount];
//                        String senderAddress = aMessage.getFrom()[0].toString();
//                        String subject = aMessage.getSubject();
//
//                        // parses recipient address in To field
//                        String toAddresses = "";
//                        Address[] listTO = aMessage.getRecipients(Message.RecipientType.TO);
//                        if (listTO != null) {
//                            for (int toCount = 0; toCount < listTO.length; toCount++) {
//                                toAddresses += listTO[toCount].toString() + ", ";
//                            }
//                        }
//                        if (toAddresses.length() > 1) {
//                            toAddresses = toAddresses.substring(0, toAddresses.length() - 2);
//                        }
//
//                        // parses recipient addresses in CC field
//                        String ccAddresses = "";
//                        Address[] listCC = aMessage.getRecipients(Message.RecipientType.CC);
//                        if (listCC != null) {
//                            for (int ccCount = 0; ccCount < listCC.length; ccCount++) {
//                                ccAddresses = listCC[ccCount].toString() + ", ";
//                            }
//                        }
//                        if (ccAddresses.length() > 1) {
//                            ccAddresses = ccAddresses.substring(0, ccAddresses.length() - 2);
//                        }
//
//                        Date sentDate = aMessage.getSentDate();
//
//                        String contentType = aMessage.getContentType();
//                        String textMessage = "";
//                        String attachFiles = "";
////                System.out.println("D:- contentType: " + contentType);
//                        if (contentType.contains("text/plain") || contentType.contains("text/html")) {
//                            textMessage = aMessage.getContent() != null ? aMessage.getContent().toString() : "";
//                        } else if (contentType.contains("multipart/")) {
//                            MimeMultipart multiPart = (MimeMultipart) aMessage.getContent();
//                            int numberOfParts = multiPart.getCount();
//                            for (int partCount = 0; partCount < numberOfParts; partCount++) {
//
//                                try {
//                                    MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
//                                    String contentMail = getText(part);
//                                    System.out.println("String :" + contentMail);
//                                    if (contentMail != null && !contentMail.equals("")) {
//                                        textMessage = contentMail;
//                                    }
//                                    BodyPart bodyPart = multiPart.getBodyPart(partCount);
//                                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
//                                        continue; // dealing with attachments only
//                                    }
//                                    InputStream is = bodyPart.getInputStream();
////                        File f = new File("D:/" + bodyPart.getFileName());
//                                    System.out.println();
//                                    //String s = ResourcesProvider.getUploadMail() + Util.createGUID() + "_" + bodyPart.getFileName().replaceAll(" ", "");
//                                    //System.out.println("Path: " + s);
//                                    String url = bodyPart.getFileName().replaceAll(" ", "");
//                                    String urlmd5 = Util.createGUID() + "_" + bodyPart.getFileName().replaceAll(" ", "");
//                                    File f = new File(ResourcesProvider.getUploadMail() + urlmd5);
//                                    FileOutputStream fos = new FileOutputStream(f);
//                                    byte[] buf = new byte[4096];
//                                    int bytesRead;
//                                    while ((bytesRead = is.read(buf)) != -1) {
//                                        fos.write(buf, 0, bytesRead);
//                                    }
//                                    fos.close();
//                                    AttachItem att = new AttachItem(url, urlmd5);
//                                    listAttach.add(att);
//                                    attachments.add(f);
//                                } catch (Exception e) {
//                                    System.out.println("Error from read mail:" + e.getMessage());
//                                    continue;
//                                }
//
//
//                            }
//
//                        }
//
////                        // prints out the message details
//////                System.out.println("Message #" + messageCount + ":");
//////                System.out.println("\t From: " + senderAddress);
//////                System.out.println("\t To: " + toAddresses);
//////                System.out.println("\t CC: " + ccAddresses);
//////                System.out.println("\t Subject: " + subject);
//////                System.out.println("\t Sent Date: " + sentDate.toString());
//////                System.out.println("\t Message: " + textMessage);
//////                System.out.println("\t Attachments: " + attachFiles);
//////                System.out.println("--------------------------------------");
//                        System.out.println("D:- Call save mail !");
//                        int pm575 = m575Store.updateM575SEVER(7, 99, subject, null, textMessage, null, Util.toSQLDate(sentDate), 0, "D", Util.removeQuotes(senderAddress), getLogin().getUserName());
//                        System.out.println("Email is save!");
//                        if (pm575 > 0 && listAttach != null) {
//                            for (AttachItem attach : listAttach) {
//                                try {
//                                    m650Store.updateM650(
//                                            0, loginSession.getLogin().getModule(), loginSession.getLogin().getCompanyNo(), 0, 0, null, 0,
//                                            "", attach.getUrl(), attach.getUrlmd5(),
//                                            0,
//                                            null, "M575", pm575, 0, null, "MAIL", 7,
//                                            loginSession.getLogin().getUserName());
//                                } catch (Exception e) {
//                                    continue;
//                                }
//                            }
//                        }
//                    } catch (Exception e) {
//                        continue;
//                    }
//
//                }
//                inbox.close(true);
//                store.close();
//                System.out.println("Inbox is close ! -- store is close !");
//            }
//
//        } catch (Exception ex) {
//            System.out.println("D:- Error from get mail sever: " + ex.getMessage());
//            ex.printStackTrace();
////            listToFromMailSever = new ArrayList<M575>();
//             showGlobalReport(true, "Không lấy được Mail từ sever !");
//            
//
//        } finally {
//            //get listmail
//            if (getLogin() != null) {
//                int idx = getLogin().getId();
//                try {
//                    listToFromMailSever = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, 0, this.getFm525(), mv276, "D",mailrevice, getLogin().getUserName());
////                    return listToFromMailSever;
//                } catch (Exception ex) {
//                    System.out.println("D: -- Error from getListM275: " + ex.getMessage());
//                    listToFromMailSever = new ArrayList<M575>();
//                }
//            } else {
//                System.out.println("D: -- Error from getListM275: ");
////            sendRedirect("login.jsp");
//                listToFromMailSever = new ArrayList<M575>();
//            }
//
//        }
//
//        return listToFromMailSever;
//    }

    public List<M575> getListToFromMailSeverD() {


        return listToFromMailSever;
    }

    

    /**
     * @param listToFromMailSever the listToFromMailSever to set
     */
    public void setListToFromMailSever(List<M575> listToFromMailSever) {
        this.listToFromMailSever = listToFromMailSever;
    }

    /**
     * @return the keysearchKH
     */
    public String getKeysearchKH() {
        return keysearchKH;
    }

    /**
     * @param keysearchKH the keysearchKH to set
     */
    public void setKeysearchKH(String keysearchKH) {
        this.keysearchKH = keysearchKH;
    }

    /**
     * @return the typesearchKH
     */
    public int getTypesearchKH() {
        return typesearchKH;
    }

    /**
     * @param typesearchKH the typesearchKH to set
     */
    public void setTypesearchKH(int typesearchKH) {
        this.typesearchKH = typesearchKH;
    }

    /**
     * @return the listdifn100
     */
    // Lít nhân vien
    public List<N100> getListdifn100() {
        try {
            CustomerStore store = new CustomerStore();
            if (SessionProvider.getSessionMapValue("KEYKH") != null) {
                keysearchKH = SessionProvider.getSessionMapValue("KEYKH").toString();
                listdifn100 = store.getListCustomer_NA(getLogin().getModule(), getLogin().getCompanyNo(), keysearchKH, 0, 1000, 0, 0, getLogin().getUserName());
                System.out.println("----list222222---------- " + listdifn100.size());
            } else {
                listdifn100 = store.getListN100DifK100(getLogin().getModule(), getLogin().getCompanyNo(), 0, 0, 1, 30, getLogin().getUserName());
                System.out.println("----list " + listdifn100.size());
            }
            SessionProvider.setSessionMapValue("listN100abc", listdifn100);
            return listdifn100;

        } catch (Exception e) {
            System.out.println("D:- Error from getListdifn100 (lay danh sach nhan vien): " + e.getMessage());
            return new ArrayList<N100>();
        }

    }

    /**
     * @param listdifn100 the listdifn100 to set
     */
    public void setListdifn100(List<N100> listdifn100) {
        this.listdifn100 = listdifn100;
    }

    /**
     * @return the listSelected
     */
    public List<N100> getListSelected() {
        return listSelected;
    }

    /**
     * @param listSelected the listSelected to set
     */
    public void setListSelected(List<N100> listSelected) {
        this.listSelected = listSelected;
    }

    public void readContent(Object o) throws IOException, MessagingException {
        if (o instanceof String) {
            System.out.println("**This is a String Message**");
            System.out.println((String) o);
        } else if (o instanceof Multipart) {
            System.out.print("**This is a Multipart Message.  ");
            Multipart mp = (Multipart) o;
            int count3 = mp.getCount();
            System.out.println("It has " + count3
                    + " BodyParts in it**");
            for (int j = 0; j < count3; j++) {
                // Part are numbered starting at 0
                BodyPart b = mp.getBodyPart(j);
                String mimeType2 = b.getContentType();
                System.out.println("BodyPart " + (j + 1) + " is of MimeType " + mp.getContentType());

                Object o2 = b.getContent();
                if (o2 instanceof String) {
                    System.out.println("**This is a String BodyPart**");
                    System.out.println((String) o2);
                } else if (o2 instanceof Multipart) {
                    System.out.print(
                            "**This BodyPart is a nested Multipart.  ");
                    Multipart mp2 = (Multipart) o2;
                    int count2 = mp2.getCount();
                    System.out.println("It has " + count2
                            + "further BodyParts in it**");
                } else if (o2 instanceof InputStream) {
                    System.out.println(
                            "**This is an InputStream BodyPart**");
                }
            } //End of for
        } else if (o instanceof InputStream) {
            System.out.println("**This is an InputStream message**");
            InputStream is = (InputStream) o;
            // Assumes character content (not binary images)
            int c;
            while ((c = is.read()) != -1) {
                System.out.write(c);
            }
        }
    }
    private boolean textIsHtml = false;

    public String getText(Part p) throws
            MessagingException, IOException {
        if (p.isMimeType("text/*")) {
            String s = (String) p.getContent();
            textIsHtml = p.isMimeType("text/html");
            return s;
        }

        if (p.isMimeType("multipart/alternative")) {
            // prefer html text over plain text
            Multipart mp = (Multipart) p.getContent();
            String text = null;
            for (int i = 0; i < mp.getCount(); i++) {
                Part bp = mp.getBodyPart(i);
                if (bp.isMimeType("text/plain")) {
                    if (text == null) {
                        text = getText(bp);
                    }
                    continue;
                } else if (bp.isMimeType("text/html")) {
                    String s = getText(bp);
                    if (s != null) {
                        return s;
                    }
                } else {
                    return getText(bp);
                }
            }
            return text;
        } else if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();

            // Dump input stream ..
            InputStream is = p.getInputStream();
            // If "is" is not already buffered, wrap a BufferedInputStream
            // around it.
            if (!(is instanceof BufferedInputStream)) {
                is = new BufferedInputStream(is);
            }
            int c;
            System.out.println("Message : ");
            while ((c = is.read()) != -1) {
                System.out.write(c);
            }


            for (int i = 0; i < mp.getCount(); i++) {
                String s = getText(mp.getBodyPart(i));
                if (s != null) {
                    return s;
                }
            }
        }

        return null;
    }

    /**
     * @return the mailrevice
     */
    public String getMailrevice() {
        return mailrevice;
    }

    /**
     * @param mailrevice the mailrevice to set
     */
    public void setMailrevice(String mailrevice) {
        this.mailrevice = mailrevice;
    }

    /**
     * @return the mailreviceId
     */
    public int getMailreviceId() {
        return mailreviceId;
    }

    /**
     * @param mailreviceId the mailreviceId to set
     */
    public void setMailreviceId(int mailreviceId) {
        this.mailreviceId = mailreviceId;
    }

    /**
     * @return the mailrevicepass
     */
    public String getMailrevicepass() {
        return mailrevicepass;
    }

    /**
     * @param mailrevicepass the mailrevicepass to set
     */
    public void setMailrevicepass(String mailrevicepass) {
        this.mailrevicepass = mailrevicepass;
    }
}
